package com.harmontronics.hanma.paas.paas.controller;


import com.harmontronics.hanma.paas.paas.service.IHmTenantUserService;
import java.sql.ResultSet;
import java.util.Arrays;

import cn.hutool.core.bean.BeanUtil;
import com.harmontronics.hanma.paas.paas.annotation.Log;
import com.harmontronics.hanma.paas.paas.annotation.TokenValidSkip;
import com.harmontronics.hanma.paas.paas.common.ResponseEntity;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.consts.BaseI18nKeyEnum;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.dto.input.HmTenantUserLoginInput;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.token.TenantUserTokenKit;
import com.harmontronics.hanma.paas.paas.token.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.harmontronics.hanma.paas.paas.dto.output.HmTenantUserResult;
import com.harmontronics.hanma.paas.paas.dto.input.HmTenantUserCreateInput;
import com.harmontronics.hanma.paas.paas.dto.input.HmTenantUserUpdateInput;
import com.harmontronics.hanma.paas.paas.domain.tenant.entity.HmTenantUser;
import com.harmontronics.hanma.paas.paas.utils.ParamUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


/**
 * 租户-管理用户表
 *
 * @author paas-generator
 * @email paas-generator@harmontronics.com
 * @date 2021-03-18 14:13:32
 */
@RestController
@RequestMapping("/api/tenant/user")
@Api(tags = {"租户-管理用户表"})
public class HmTenantUserController {
    @Autowired
    private IHmTenantUserService hmTenantUserService;

    @Autowired
    private TenantUserTokenKit tenantUserTokenKit;

    @Value("${mos.oss.enabled:false}")
    private Boolean mosEnabled;


    /**
     * 分页列表
     */
    @GetMapping("/page/list")
    @ApiOperation("分页列表")
    public ResponseEntity<PageBase<HmTenantUserResult>> list(@ApiParam(value = "页码", defaultValue = "1") @RequestParam(required = false, defaultValue = "1") int pageNo,
                                                             @ApiParam(value = "每页数据条数", defaultValue = "20") @RequestParam(required = false, defaultValue = "20") int pageSize,
                                                             @RequestParam(required = false) String tenantUserName) {
        //只有管理员可以管理用户
        /**
         if(RequestUtils.getIsAdmin()!= NumberEnum.ONE.getNum()){
         throw new ErrorKeyException(I18nKeyEnum.REQUEST_INVALID);
         }*/
        PageBase<HmTenantUser> hmTenantUserPageBase = hmTenantUserService.getList(pageNo, pageSize, tenantUserName);
        PageBase<HmTenantUserResult> resultPageBase = new PageBase<>();
        if(hmTenantUserPageBase != null){
            resultPageBase = PageBase.copy(hmTenantUserPageBase, HmTenantUserResult.class);
        }
        return ResponseEntity.ok(resultPageBase);
    }


    /**
     * 信息
     */
    @GetMapping("/info")
    @ApiOperation("详情")
    @TokenValidSkip
    public ResponseEntity<HmTenantUserResult> info(@ApiParam(name = "id", value = "租户用户ID", required = true) @RequestParam Long id) {
        HmTenantUser hmTenantUser = hmTenantUserService.findById(id);
        //非管理员不可以查看其它用户
        hmTenantUserService.isAdmin(hmTenantUser);
        HmTenantUserResult result = BeanUtil.toBean(hmTenantUser, HmTenantUserResult.class);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存
     */
    @PostMapping()
    @ApiOperation("保存")
    @Log("新增了管理用户")
    public ResponseEntity<String> save(@Valid @RequestBody HmTenantUserCreateInput hmTenantUserInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmTenantUser hmTenantUser = BeanUtil.toBean(hmTenantUserInput, HmTenantUser.class);
        hmTenantUserService.save(hmTenantUser);

        return ResponseEntity.ok();
    }


    /**
     * 删除
     */
    @DeleteMapping()
    @ApiOperation("删除")
    @Log("删除了管理用户")
    public ResponseEntity<String> delete(@RequestBody Long[] ids) {
        UserInfo userInfo = tenantUserTokenKit.getUserInfo();
        //只有管理员可以管理用户
        if (!userInfo.isAdmin()) {
            throw new ErrorKeyException(BaseI18nKeyEnum.REQUEST_INVALID);
        }
        hmTenantUserService.remove(Arrays.asList(ids));
        return ResponseEntity.ok();
    }

    @DeleteMapping("logout")
    @ApiOperation(value = "退出登录")
    @TokenValidSkip
    public ResponseEntity logout(HttpServletRequest request) {
        hmTenantUserService.logout();
        return ResponseEntity.ok();
    }

    @PostMapping("login")
    @ApiOperation(value = "租户用户登录")
    @TokenValidSkip
    public ResponseEntity login(@Valid @RequestBody HmTenantUserLoginInput hmTenantUserLoginInput, BindingResult bindingResult) {
        ParamUtils.valid(bindingResult);
        HmTenantUser hmTenantUser = BeanUtil.toBean(hmTenantUserLoginInput, HmTenantUser.class);
        hmTenantUser.setUserName(hmTenantUserLoginInput.getUserName());
        return ResponseEntity.ok(hmTenantUserService.login(hmTenantUser));
    }

    /**
     * 通过Token获取用户信息
     */
    @GetMapping("/userinfo")
    @ApiOperation("通过Token获取用户信息")
    public ResponseEntity<HmTenantUserResult> userinfo() {
        UserInfo userInfo = hmTenantUserService.getUserByToken();
        HmTenantUserResult result = new HmTenantUserResult();
        result.setUserName(userInfo.getUserName());
        result.setId(userInfo.getUserId());
        result.setTenantId(userInfo.getTenantId());
        result.setTenantName(userInfo.getTenantName());
        result.setIsAdmin(userInfo.isAdmin() ? 1 : 0);
        return ResponseEntity.ok(result);
    }

    /**
     * 租户用户表单字段验证
     */
    @GetMapping("/validate-field")
    @ApiOperation(value = "租户用户表单字段验证")
    public ResponseEntity<String> validateField(
            @ApiParam(name = "key", value = "key", required = true) @RequestParam String key,
            @ApiParam(name = "value", value = "value", required = true) @RequestParam String value) {
        hmTenantUserService.validateField(key, value);
        return ResponseEntity.ok();
    }

    @PutMapping("reset-pwd")
    @ApiOperation("重置密码")
    @Log("管理用户重置了密码")
    public ResponseEntity<String> resetPassword(@Valid @RequestBody HmTenantUserUpdateInput hmTenantUserUpdateInput) {
        HmTenantUser hmTenantUser = BeanUtil.toBean(hmTenantUserUpdateInput, HmTenantUser.class);
        hmTenantUserService.resetPassword(hmTenantUser);
        return ResponseEntity.ok();
    }

    /**
     * 更新状态(禁用、启用) 0:启用 1：禁用
     */
    @PutMapping("/update-status")
    @ApiOperation("更新状态")
    @Log("修改了管理用户的状态")
    public ResponseEntity<String> updateStatus(@RequestBody HmTenantUserUpdateInput hmTenantUserUpdateInput) {
        if (hmTenantUserUpdateInput.getId() == null || hmTenantUserUpdateInput.getStatus() == null
                || hmTenantUserUpdateInput.getStatus() < NumberEnum.ZERO.getNum() || hmTenantUserUpdateInput.getStatus() > NumberEnum.ONE.getNum()) {
            return ResponseEntity.error(BaseI18nKeyEnum.REQUEST_PARAM_ERROR);
        }

        hmTenantUserService.updateStatus(hmTenantUserUpdateInput.getId(), hmTenantUserUpdateInput.getStatus());
        return ResponseEntity.ok();
    }

    @GetMapping("/mos-enabled")
    @ApiOperation("部署方式")
    @TokenValidSkip
    public ResponseEntity<Boolean> getDeploymentWay(){
        return ResponseEntity.ok(mosEnabled);
    }


}
